package org.dlsu.mt.parser.TRANSFER;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

import org.dlsu.mt.parser.FStructure;
import org.dlsu.mt.parser.FStructureElement;
import org.dlsu.mt.parser.FStructureElementString;
import org.dlsu.mt.parser.FStructureElementValue;
import org.dlsu.mt.parser.FStructureInterface;
import org.dlsu.mt.parser.SemEntry;
import org.dlsu.mt.parser.dictionary.DictionaryWord;
import org.dlsu.mt.parser.dictionary.Global;

public class Transfer{
	
	private Global glob;
	private boolean successfulRestore;	
	private Vector fstructuresToBuild;
	
	private Vector ambiguities;
	
	//private int elementCounter;
	//private Vector skipCounter;
	//private int currentRule;
			
	public Transfer(Global global){
		
		glob = global;
	}
	
	public Transfer(){
		
		glob = new Global();
		
		glob.setLang1Dict(new org.dlsu.mt.parser.dictionary.Dictionary("Language1"));
		glob.setLang2Dict(new org.dlsu.mt.parser.dictionary.Dictionary("Language2"));	
	}
	
	public FStructure transfer(FStructure f, char lang)
	{
		glob.logWriter.println("Entering the transfer phase...");
		
		System.out.println("Entering the transfer phase...");
		
		FStructure root = new FStructure("TOP");
		
		f.setName(f.getName().toUpperCase());
		
		root.addEntry(f);		
		
		System.out.println("GIANGIAN");
		
		FStructure struct = startTransfer(root, lang);
		
		struct.setName("root");
					
		saveOutputToFile(struct, "/home/pckid/LEFT/transferOutput.xml");
		
		glob.logWriter.println("Exiting the transfer phase...");
		
		return struct;
	}
	

	public String disambiguator(String arr[], String semantics, String lang){
		
		String query;
		String wordInfo[];
		
		glob.logWriter.print("candidate translations: ");
		
		for(int j = 0; j < arr.length; j++){
			glob.logWriter.print(arr[j] + " ");
		}
		
		glob.logWriter.println("");
		
		try{
   			
			Class.forName("com.mysql.jdbc.Driver");
	        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/leftDB", "root","");
			
   			Statement stmt = con.createStatement();
   			
   			for(int i = 0; i<arr.length; i++){
   				   				
   				wordInfo = arr[i].split(" ");
   				   				
   				String word = wordInfo[0];
   				  				   				
   				if(lang.equals("1"))
   					query = "SELECT * FROM language1Dict WHERE word = '"+word+"'";
   				else
   					query = "SELECT * FROM language2Dict WHERE word = '"+word+"'";
   				
   				ResultSet rs = stmt.executeQuery(query);
   				
   				while(rs.next()){
   					String temp = rs.getString("semantics");
   					glob.logWriter.println(temp + " semantics");
   					
   					if(temp!=null){
   						
   						String[] tempArr = temp.split(", ");
   						int n = 0;
   							
   						while(n < tempArr.length){   							
   							
   							glob.logWriter.println(tempArr[n] + " semantics after tokenizing");
   							glob.logWriter.println(semantics + " semantics of original word");
   							   							
   							if(tempArr[n].equals(semantics)){
   								
   								glob.logWriter.println("semantics matched: " + semantics);
   								return arr[i];
   							}
   							n++;
   						}  						
   					}		
   				}   			
   			}
   			
   			return arr[0];   				
   			
   		}catch(Exception e){
   			
   		}
		
		return arr[0];
	}
	
		
	private FStructure buildFStructure(String name){
		
		FStructure root = new FStructure(name);
		Vector fstructRemainingValues = new Vector();
		
		Iterator i = fstructuresToBuild.iterator();
		boolean cont = true;
		
		/* FIRST STEP IN BUILDING THE OUTPUT */
		
		while(i.hasNext() && cont){
			FStructure fstruct = (FStructure)i.next();			
			if(fstruct.getName().equals(name)){
				//glob.transferDictionary.display(fstruct);
				root = fstruct;
				fstructuresToBuild.remove(fstruct);
				cont = false;
			}
		}
		
		/* SECOND STEP IN BUILDING THE OUTPUT */
		
		
		i = fstructuresToBuild.iterator();
		cont = true;
		
		while(i.hasNext()){
			FStructure fstruct = (FStructure)i.next();			
			if(fstruct.getPosition().equals(name)){
				//System.out.println("The value of " + name + " fstructure has been found.");
				root.addEntry(fstruct);
			}
			else
				fstructRemainingValues.add(fstruct);
		}
		
		fstructuresToBuild = fstructRemainingValues;
				
		/* THIRD STEP IN BUILDING THE OUTPUT */	
		
		Enumeration e = root.values.keys();
		
		while(e.hasMoreElements()){
			
			FStructureInterface fsi = root.getEntry((String)e.nextElement());
			
			if(fsi instanceof FStructure){
				
				FStructure fs = restoreFStructure((FStructure)fsi);
				root.values.remove(fs.getName());
				root.addEntry(fs);								
			}
		}	
		//glob.transferDictionary.display(root);
		
		return root;
	}
	
	private FStructure restoreFStructure(FStructure f){
		
		Vector fstructRemainingValues = new Vector();
		
		Iterator i = fstructuresToBuild.iterator();
		FStructure root = (FStructure)f.clone();
						
		while(i.hasNext()){
			FStructure fstruct = (FStructure)i.next();			
			if(fstruct.getPosition().equals(root.getName())){
				System.out.println("The value of " + root.getName() + " fstructure has been found.");
				root.addEntry(fstruct);
			}
			else
				fstructRemainingValues.add(fstruct);
		}
		fstructuresToBuild = fstructRemainingValues;
		
		Enumeration e = root.values.keys();
		
		while(e.hasMoreElements()){
			
			FStructureInterface fsi = root.getEntry((String)e.nextElement());
			
			if(fsi instanceof FStructure){
				
				FStructure fs = restoreFStructure((FStructure)fsi);
				root.values.remove(fs.getName());
				root.addEntry(fs);								
			}
		}				
		return root;
	}
		
	public FStructure startTransfer(FStructure input, char lang){
		
				
		fstructuresToBuild = new Vector();
		ambiguities = new Vector();
		
		glob.transferDictionary.display(input);
		System.out.println("GIANX");
		FStructure output = transferF(input, lang);
		
		//build output with fstructureToBuild		
		
		/*
		Iterator i = fstructuresToBuild.iterator();
		
		while(i.hasNext()){
			System.out.println("SIMULA");
			FStructure f = (FStructure)i.next();			
			System.out.println(f.getPosition() + " this is the position");
			glob.transferDictionary.display(f);
			System.out.println("tapos na ang values ni fstructuresToBuild");
		}
		*/
		//System.out.println("value ng nireturn ni transferf");

		//output = (FStructure)output.getEntry("ROOT");
		
		//if(output == null)	
		//	System.out.println("the output is null");
		
		output = buildFStructure("ROOT");
		
		//System.out.println(output.checkSemanticEntries(null));
		
		output = fixSemEntries(output);
		
		//glob.transferDictionary.display(output);
		
		return output;
	}	
	
	public FStructure fixSemEntries(FStructure f){
		
		FStructure fs = (FStructure)f.clone();
								
		//glob.transferDictionary.display(fs);
		//while(sentenceTokens.hasNext()){
		//for(int c = 0; c < tokVec.size(); c++){
			
		Iterator i = ambiguities.iterator();
		
		while(!fs.checkSemanticEntries(null) && i.hasNext()){
				
			FStructureElement fse = (FStructureElement)i.next();
										
			//System.out.println(fse.getName() + " " + fse.values.toString());
			fs = forceTraverse(fs, fse);
		}		
		
		FStructure oldVal = (FStructure)fs.clone();
		
		try{
			
			Iterator j = ambiguities.iterator();
			
			while(!checkSem(fs) && j.hasNext()){
				
				FStructureElement fse = (FStructureElement)j.next();											
				//System.out.println(fse.getName() + " " + fse.values.toString() + " andito na men");
				fs = forceTraverse(fs, fse);
							
			}	
		}catch(Exception e){
			fs = oldVal;
		}
		
				
		if(fs.checkSemanticEntries(null))
			return fs;
		else
			return f;
	}
	
	
	public boolean compareValues(FStructureElement fse, FStructureElement fse2){
		
		Iterator i = fse.values.iterator();
		Iterator n = fse2.values.iterator();
				
		while(i.hasNext()){		
			while(n.hasNext()){
				if(i.next() == n.next()){
					return true;
				}
			}	
		}
		return false;		
	}		
	
	public FStructure transferF(FStructure g, char lang)
	{
		//initialization of whatever necessary		
		//temporary code
		FStructure outputF = new FStructure(g.getName());
		FStructure tempF = new FStructure(g.getName());
		FStructure f = (FStructure)g.clone();
		
		//f.setName(f.getName().toUpperCase());
		//f = getEquivalentFStructure(f, lang);
		//f.setName(f.getName().toLowerCase());	
		
		//Vector<String> keys = f.getKeys();
		Enumeration e = f.values.keys();	
		
		//if(keys != null)
		
			//for(int i = 0; i < keys.size(); i++)
			while(e.hasMoreElements())
			{
				String key = (String)e.nextElement();
				
				FStructureInterface elem = f.getEntry(key);				
				FStructure out = null;
								
				if(elem instanceof FStructure)
				{	
					
					Vector values;					
					FStructure elemF = (FStructure)elem;
						
					out = transferF(elemF,lang);
						
					Vector v = elemF.getKeys();
					Iterator i = v.iterator();
					
					while(i.hasNext()){
						String test = (String)i.next();
						FStructureInterface fsi = elemF.getEntry(test);
						if(fsi instanceof FStructure)
							if(out.getEntry(test) == null)
								elemF.values.remove(test);
					}
						
					elemF.setPosition(f.getName());
					
					elemF = getEquivalentFStructure(elemF, out, lang);
										
					if(elemF != null){			
						//System.out.println(elemF.getPosition() + " THIS IS THE POSITION AFTER INSTANTIATION");						
						//values = traverse(out);
						//elemF = restoreElements(elemF, values);
						fstructuresToBuild.add(elemF);	
							
					}
					else	
						outputF.addEntry(out);					
					
				}
				else if(elem instanceof FStructureElement)
				{
					FStructureElement element = (FStructureElement)elem;
					
					element.setPrevParentPosition(f.getName());
													
					FStructureElement word = transferFElement(element, lang);
														
					outputF.addEntry(word);					
				}
			}
		
		return outputF;
	}
	
	
	public FStructure getEquivalentFStructure(FStructure fstruct, FStructure transValFstruct, char lang){		
		
		int limit = glob.transferDictionary.getMaxRuleID();
		int counter = 1;
		
		FStructure tempOutput = null;
		int emptyCounter = 0;
		
		FStructure output;
		TransferRule cond;
		Vector values = new Vector();
		
		glob.logWriter.println("Getting equivalent f-structure..");		
	
		values = traverse(transValFstruct);
		
		System.out.println(values.toString() + "abot hanggang dito");
		
		fstruct = clearElements(fstruct);
		
		while(counter <= limit){
		
			cond = glob.transferDictionary.getTransferRule(counter);
			//currentRule = counter;
			
			
			if(cond == null){
				
				glob.logWriter.println("null -- unsuccessful building transfer rule number " + counter);				
			}			
			else{				
				
				if(lang == '1'){
																					
					boolean eq = checkIfEqual(fstruct, cond.getLanguage1FStructure());
					
					if(eq){
						System.out.println(counter + " this is the rule");
						glob.logWriter.println("Transfer rule found.. rule number = " + counter);
						
						output = cond.getLanguage2FStructure();						
						//System.out.println(output.getPosition() + " THIS IS THE POSITION AFTER INSTANTIATION");
											
						glob.logWriter.println("f-structure of opposite language instantiated..");
						
						//glob.logWriter.println("restoring values and retained f-elements");
						
						output = restoreElements(output, cond.getLanguage2RetainedFElements());					
						output = restoreElements(output, values);						
						
						int tempEmptyCounter = thereIsEmpty(output);
						
						if(tempEmptyCounter < emptyCounter){
							emptyCounter = tempEmptyCounter;
							tempOutput = (FStructure)output.clone();
						}
												
						if(tempEmptyCounter == 0)
							return output;
						else
							System.out.println("wrong rule wrong rule wrong rule wrong rule");					
					}			
				}
				else if(lang == '2'){				
										
					boolean eq = checkIfEqual(fstruct, cond.getLanguage2FStructure());
					
					if(eq){						
						System.out.println(counter + " this is the rule");
						glob.logWriter.println("Transfer rule found.. rule number = " + counter);
						output = cond.getLanguage1FStructure();	
						//System.out.println(output.getPosition() + " THIS IS THE POSITION AFTER INSTANTIATION");
						
						glob.logWriter.println("f-structure of opposite language instantiated..");											
						
						//glob.logWriter.println("restoring values and retained f-elements");
						
						output = restoreElements(output, cond.getLanguage1RetainedFElements());						
						output = restoreElements(output, values);
						
						int tempEmptyCounter = thereIsEmpty(output);
						
						if(tempEmptyCounter < emptyCounter){
							emptyCounter = tempEmptyCounter;
							tempOutput = (FStructure)output.clone();
						}
												
						if(tempEmptyCounter == 0)
							return output;
						else
							System.out.println("wrong rule wrong rule wrong rule wrong rule");					
						
					}				
				}	
			}		
			counter++;
		}
		
		//fstruct = restoreElements(fstruct, origValues);
		//System.out.println("UMABOT DITO");
		//return output;
		
		if(tempOutput != null)
			return tempOutput;
		else
			return null;
	}
	
	public int thereIsEmpty(FStructure f){
		
		FStructure fstruct = (FStructure)f.clone();
		Vector v = traverse(fstruct);
		int emptyCounter = 0;
		
		Iterator i = v.iterator();
		
		while(i.hasNext()){
			FStructureElement fElem = (FStructureElement)i.next();
			if(fElem.values.isEmpty()){
				System.out.println(fElem.getName() + " HAS EMPTY VALUE");
				//return true;
				emptyCounter++;
			}
		}
		
		System.out.println(f.getName() + " VALUE");
		return emptyCounter;		
	}
		
	public boolean checkIfEqual(FStructure basis, FStructure tbc){
		
		glob.logWriter.println(basis.getName() + " being matched with " + tbc.getName());
		
		//System.out.println(basis.getName() + " " + basis.getKeys().toString());
		//System.out.println(tbc.getName() + " " + tbc.getKeys().toString());
		//glob.transferDictionary.display(basis);		
		//glob.transferDictionary.display(tbc);
		//System.out.println("GGGGGGGGGGGGGGGGGGGGGGGGGGGGG");
		
		if(basis.equals(tbc) && basis.getPosition().equals(tbc.getPosition())){
			//glob.logWriter.println(basis.getName() + ":" + basis.getKeys().toString() + " matches with " + tbc.getName() + ":" + tbc.getKeys().toString());
			//System.out.println("ENTERING THE IF CONDITION");
			//System.out.println(basis.getName() + " --- " + tbc.getName());
			//System.out.println(basis.getKeys().toString() + " basis keys");
			//System.out.println(tbc.getKeys().toString() + " tbc keys");
			return true;		
		}
		else{
			//glob.logWriter.println(basis.getName() + ":" + basis.getKeys().toString() + " does not match with " + tbc.getName() + ":" + tbc.getKeys().toString());
			//System.out.println("WILL NOT ENTER THE IF CONDITION");
			//System.out.println(basis.getName() + " --- " + tbc.getName());
			//System.out.println(basis.getKeys().toString() + " basis keys");
			//System.out.println(tbc.getKeys().toString() + " tbc keys");
			
			//System.out.println(tbc.toXML());
			return false;
		}
		//ROOT FS: ROOT COMPLEMENT XCOMP OBJOFPREP1 PPADJUNCT OBJOFPREP2 SUBJ FE: prep1 prep2 proper_noun det noun pronoun verb FORMAT: OBJOFPREP2proper_noun PPADJUNCTprep2OBJOFPREP2 OBJOFPREP1PPADJUNCTdetnoun XCOMPprep1OBJOFPREP1 COMPLEMENTXCOMP SUBJpronoun ROOTCO
		
		/*
		Vector v = new Vector();
		Vector a = new Vector();
		Vector b = new Vector();
		FStructure fs;
		
		if(basis.getName().equals(tbc.getName())){
			//System.out.println("NAME MATCH " + basis.getName());
			v = basis.getKeys();
			a = tbc.getKeys();
			
			//System.out.println("basis -- " + v.toString());
			//System.out.println("tbc -- " + a.toString());
			
			int i = 0;
			while(i < a.size()){
				
				b.addElement((FStructureInterface)basis.getEntry((String)a.elementAt(i)));
				FStructureInterface fsi = (FStructureInterface)b.elementAt(i);
								
				if(fsi != null){
					if(!fsi.equals((FStructureInterface)tbc.getEntry((String)a.elementAt(i))))
						return false;
					else
						i++;
				}
				else
					return false;		
			}			
		}
		else
			return false;
			
		return true;
		*/
	}
	
	public FStructure restoreElements(FStructure f, Vector vec){
				
		Enumeration e = vec.elements();
		
		//System.out.println(vec.toString());
		
		while(e.hasMoreElements()){
			
			FStructureElement elem = (FStructureElement)e.nextElement();
			//System.out.println(elem.values.toString());
			glob.logWriter.println("values to be restored: " + elem.values.toString());
			
			successfulRestore = false;			
			f = traverse(f, elem);
		}
		
		return f;
	}
	
	public FStructure clearElements(FStructure f){
		
		FStructureInterface fsi;
		FStructure fstruct;
		String key;
		
		glob.logWriter.println("Clearing " + f.getName() + "...");
		
		Enumeration e = f.values.keys();
		
		for(int i = 0; i < f.values.size();i++){
			key = (String)e.nextElement();
			fsi = f.getEntry(key);
			
			if (fsi instanceof FStructureElement){
				
				glob.logWriter.println("f-structure element found: " + key + " ");
				f.values.remove(key);
				FStructureElement newElem = new FStructureElement(key);
				f.values.put(key, newElem);
								
				glob.logWriter.println("cleared..");
				//fElem.add((FStructureElement)fsi);
				
			}
				//return (FStructureElement)fsi;
			
			else{				
				fstruct = (FStructure)fsi;
				if(fstruct.values.size() != 0){
					
					FStructure temp = clearElements(fstruct);					
					
					f.values.remove(key);
					f.values.put(key, temp);
					
				}
			}
		}		
		return f;
	}
	
	public Vector traverse(FStructure f){
		
		FStructureInterface fsi;
		FStructure fstruct;
		Vector fElem = new Vector();
		
		glob.logWriter.println("traversing " + f.getName());
		
		Enumeration e = f.values.keys();
		
		for(int i = 0; i < f.values.size();i++){
			
			fsi = f.getEntry((String)e.nextElement());
			
			if (fsi instanceof FStructureElement){
				
				glob.logWriter.println("f-structure element found: " + fsi.getName());
				FStructureElement fse = (FStructureElement)fsi;
				fse.setPrevParentPosition(f.getName());
				
				System.out.println(fse.values.toString() + " values of " + fse.getName());
				
				fElem.add(fse);	
				glob.logWriter.println("stored");
			}			
			else{				
				fstruct = (FStructure)fsi;
				if(fstruct.values.size() != 0){
					Vector add = traverse(fstruct);
					Enumeration en = add.elements();
					
					while(en.hasMoreElements()){
						
						FStructureElement fse = (FStructureElement)en.nextElement();
						//fse.setPrevParentPosition();
						fElem.add(fse);
					}					
				}
			}
		}		
		return fElem;
	}
	
	
	public FStructure forceTraverse(FStructure f, FStructureElement fse){
		
		FStructureInterface fsi;
		String key;
		Enumeration e = f.values.keys();		
				
		for(int i = 0; i < f.values.size();i++){
			
			key = (String)e.nextElement();
			fsi = f.getEntry(key);
			
			if (fsi instanceof FStructureElement){
				FStructureElement fsiElement = (FStructureElement)fsi;
				
				if(fsiElement.getName().equals(fse.getName())){
					
					if(fsiElement.getPrevParentPosition().equals("") || fse.getPrevParentPosition().equals(fsiElement.getPrevParentPosition())){
						//System.out.println(fsiElement.getPrevParentPosition() + " this is the prev value");
						//glob.logWriter.println("restoration successful..");
						System.out.println("SUCCESSFUL RESTORATION");
						//elementCounter++;
						f.values.remove(key);						
						f.values.put(key, fse);												
						//successfulRestore = true;				
					}
					
				}				
				
				System.out.println("UNSUCCESSFUL RESTORATION " + fsiElement.getName());
			}	
			else{					
				fsi = forceTraverse((FStructure)fsi, fse);
				f.values.remove(key);				
				f.values.put(key, fsi);				
			}				
		}		
			
		return f;		
	}
	
	public boolean checkSem(FStructure f){
		
		
		Vector v = traverse(f);
		Iterator it = v.iterator();
		
		FStructureElement fse = (FStructureElement)it.next();
		Vector sem = fse.getSemEntries();
		
		System.out.println(fse.getName() + " " + fse.values.toString() + " checkSem function");
		v.remove(fse);
		
		it = v.iterator();
		
		while(it.hasNext()){
		
			FStructureElement fsElem = (FStructureElement)it.next();
			
			for(int j = 0; j < sem.size(); j++){
				
				if(fsElem.compareSemAttribute((SemEntry)sem.elementAt(j))){
					System.out.println(((SemEntry)sem.elementAt(j)).getAttribute() + " match with an attribute");
					if(!fsElem.compareSemEntry((SemEntry)sem.elementAt(j))){
						System.out.println(((SemEntry)sem.elementAt(j)).getValue() + " no match with a value");
						return false;										
					}
				}				
			}
		}
		
		return true;	
	}
	
	public FStructure traverse(FStructure f, FStructureElement fse){
		
		FStructureInterface fsi;
		String key;
		Enumeration e = f.values.keys();
				
		for(int i = 0; i < f.values.size();i++){
			
			key = (String)e.nextElement();
			fsi = f.getEntry(key);
			
			if (fsi instanceof FStructureElement){
				FStructureElement fsiElement = (FStructureElement)fsi;
				
				if(fsiElement.getName().equals(fse.getName()) && fsiElement.values.isEmpty() && !successfulRestore){
					
					if(fsiElement.getPrevParentPosition().equals("") || fse.getPrevParentPosition().equals(fsiElement.getPrevParentPosition())){
						//System.out.println(fsiElement.getPrevParentPosition() + " this is the prev value");
						glob.logWriter.println("restoration successful..");
						//elementCounter++;
						f.values.remove(key);
						f.values.put(key, fse);												
						successfulRestore = true;				
					}
					
				}
			}	
			else if(fsi instanceof FStructure){
					
				fsi = traverse((FStructure)fsi, fse);
				f.values.remove(key);				
				f.values.put(key, fsi);				
			}				
		}		
			
		return f;		
	}
	
	public FStructureElement transferFElement(FStructureElement fsElem, char lang)
	{
		
		FStructureElement fs = (FStructureElement)fsElem.clone();	
		
		Iterator i = fs.values.iterator();
		String word; //prevVal = "";
		String sem = "";
		String temp = "";
		
		DictionaryWord dw;
		
		while(i.hasNext()){
			
			FStructureElementString fes = (FStructureElementString)i.next();
			temp = (String)fes.toString();
			
			//glob.logWriter.println(temp + " value of temp before check if startswith SEM");
			
			if(temp.startsWith("SEM", 0)){				
				sem = temp.substring(4);
				glob.logWriter.println(sem + " getting the semantics");
			}			
		}
		
		glob.logWriter.println(sem + " semantics found");
		
		i = fs.values.iterator();
		
		while(i.hasNext()){
						
			FStructureElementString fes = (FStructureElementString)i.next();
			word = (String)fes.toString();
			String arr[];
			
			if(word.startsWith("PRED", 0)){
				
				word = word.substring(5);
				
				glob.logWriter.println("translating " + word + " " + fsElem.getName());
								
				if(lang == '1'){
					try{					
						String[] transArr = glob.transferDictionary.getPosTranslationWords(word, "1", fs.getName());
						
						if(transArr.length > 1){
							
							for(int j = 0; j < transArr.length; j++){
								String[] temp2 = transArr[j].split(" ");
								System.out.println(temp2[0] + " " + temp2[1] + " POSSIBLE TRANSLATIONS");
								
								
								
									FStructureElement fsTemp = glob.language2Dictionary.lookup(temp2[0], temp2[1]);
									fsTemp.setPrevParentPosition(fsElem.getPrevParentPosition());
									ambiguities.add(fsTemp);
								
							}
							
						}
						word = disambiguator(transArr, sem, "2");
						
					}catch(Exception ex){
						word = word + " " + fs.getName();
						//System.out.println(word);
					}
					
					glob.logWriter.println("new value -- " + word);
						
					arr = word.split(" ");
					
					fs = glob.language2Dictionary.lookup(arr[0],arr[1]);
					fs.setPrevParentPosition(fsElem.getPrevParentPosition());
														
				
				}
				else{					

					try{
												
						String[] transArr = glob.transferDictionary.getPosTranslationWords(word, "2", fs.getName());
						
						if(transArr.length > 1){
							
							for(int j = 0; j < transArr.length; j++){
								String[] temp2 = transArr[j].split(" ");
								System.out.println(temp2[0] + " " + temp2[1] + " POSSIBLE TRANSLATIONS");
								
																
									FStructureElement fsTemp = glob.language1Dictionary.lookup(temp2[0], temp2[1]);
									fsTemp.setPrevParentPosition(fsElem.getPrevParentPosition());
									ambiguities.add(fsTemp);
								
								//ambiguities.add(glob.language1Dictionary.lookup(temp2[0], temp2[1]));
							}
							
						}
							
						word = disambiguator(transArr, sem, "1");
						
					}catch(Exception ex){
						word = word + " " + fs.getName();
					}
					
					glob.logWriter.println("new value -- " + word);
					
					arr = word.split(" ");
					
					fs = glob.language1Dictionary.lookup(arr[0],arr[1]);
					fs.setPrevParentPosition(fsElem.getPrevParentPosition());
					
				}			
				
				return fs;							
			}			
		}		
		return fs;	
	}
	
	
	
	
	
	public void saveOutputToFile(FStructure f, String filename){
		
		FStructureInterface fsi;
		
		String sentence = "";
		
		try{
		
			PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
			
			pw.println("<?xml version='1.0' ?>");
			pw.println("<DOCUMENT sentence_count=\""+ "1" +"\">");
			pw.println("<SEMANTICS>");
			pw.println("<attribute name=\""+f.getName() +"\" type=\"structure\">\n");
			
			Enumeration e = f.values.keys();
			
			//pw.println(f.toXML());			
			while(e.hasMoreElements()){
							
				fsi = f.getEntry((String)e.nextElement());							
				writeToFile(fsi, pw);
			}
			
			pw.println("</attribute>\n");
			pw.println("</SEMANTICS>");		
			pw.println("</DOCUMENT>");
			pw.close();
			
		}catch(Exception e){
			
		}
	}
	
	public void writeToFile(FStructureInterface fsi, PrintWriter pw){
		
		Iterator i;
		String key;		
				
			if (fsi instanceof FStructure){
				
				FStructure f = (FStructure)fsi;
				
				i = f.values.values().iterator();
				
				pw.println("<attribute name=\""+fsi.getName() +"\" type=\"structure\">\n");
				while(i.hasNext())
				{	
					writeToFile((FStructureInterface)i.next(), pw);
				}		
				pw.println("</attribute>\n");
								
			}
			else{
				
				FStructureElement fe = (FStructureElement)fsi;
				
				i = fe.values.iterator();
				
				pw.println("<attribute name=\""+fe.getName()+"\" type=\"element\">\n");
				while(i.hasNext())
				{
					pw.println(((FStructureElementValue) i.next()).toXML());					
				}
				pw.println("</attribute>\n");		
			}
	}
	
}
